import { serialize } from '/lib/node_modules/@shoelace-style/shoelace/dist/utilities/form.js';
class Register {
    constructor() {
        this.systemLocalStorage = new SystemLocalStorage();
        this.showAddress();
        this.ajax = new Ajax();
        this.login();
    }
    websocket() {
        let that =this;
        const client = new WebSocketClient();
        that.clientId =parseInt( that.generateStrictLongId());
        client.init({
            url: `http://10.10.14.129:9055/messagenotificationmanagement/websocket`,
            subscriptions: [
                {
                    topic: '/topic/system',
                    callback: (msg) => console.log('系统消息:', msg)
                },
                {
                    topic: `/user/${that.clientId}/queue/private`,
                    callback: (msg) => console.log('私有消息:', msg)
                },
                {
                    topic: `/user/LHT_001/queue/private`,
                    callback: (msg) => console.log('私有消息:', msg)
                },
            ],
            onopen: (frame) => {
                console.log('连接成功');
                client.sendMessage();
            },
            onerror: (err) => console.error('连接异常',err)
        });
    }
    generateStrictLongId() {
        // 1. 时间戳（42位，兼容到 2100 年）
        const timestamp = Date.now() - 1609459200000; // 从 2021-01-01 开始的毫秒数
        const timestampBits = timestamp.toString(2).padStart(42, '0').substring(0, 42);
      
        // 2. 机器/会话标识（10位，基于浏览器指纹）
        const machineId = this.getBrowserFingerprint().toString(2).padStart(10, '0').substring(0, 10);
      
        // 3. 随机序列（12位）
        const randomBits = Math.floor(Math.random() * 4096).toString(2).padStart(12, '0');
      
        // 4. 合并位并转换为十进制字符串
        const fullBinary = timestampBits + machineId + randomBits;
        const idValue = BigInt('0b' + fullBinary);
      
        // 5. 确保在 Long 范围内
        const maxLong = BigInt('9223372036854775807');
        return idValue <= maxLong 
          ? idValue.toString() 
          : (idValue - maxLong - BigInt(1)).toString(); // 溢出处理
    }
    getBrowserFingerprint() {
        const fingerprint = [
          navigator.userAgent,
          navigator.platform,
          navigator.hardwareConcurrency || 'unknown',
          screen.width,
          screen.height
        ].join('|');
        return this.hashCode(fingerprint) % 1024; // 10位 = 0-1023
    }
    hashCode(str) {
    let hash = 0;
    for (let i = 0; i < str.length; i++) {
        hash = (hash << 5) - hash + str.charCodeAt(i);
        hash |= 0;
    }
    return Math.abs(hash);
    }
    register(data) {
        let that = this;
        data.clientId =that.clientId ;
        that.ajax.post({
            url: "http://10.10.14.129:9055/usermanagement/register",
            data: data,
            beforeCallback: function(){
                that.loading.exhibit = !that.loading.exhibit;
            },
            successCallback: function (res) {
                console.log(res)
            }, 
            errorCallback: function () {

            }, 
            completeCallback: function () {
                that.loading.exhibit = !that.loading.exhibit;
            }
        })
    }
    login() {
        let that = this;
        that.ajax.post({
            url: "http://10.10.14.129:9055/accountpermissionsmanagement/login",
            data: "LHT_001",
            successCallback: function (res) {
                console.log(res)
            }, 
            errorCallback: function () {

            }, 
            completeCallback: function () {
                console.log(that.loading.exhibit)
                // that.loading.exhibit = !that.loading.exhibit;
            }
        })
    }
    async showAddress() {
        document.getElementById("address-content").innerHTML =
            `<wcs-selector-address id="address">
                <script type="application/json">
                 ${JSON.stringify(this.getAddressData())}
                </script>
            </wcs-selector-address>`;
        const picker = document.querySelector('wcs-selector-address');
        picker.country = "US";
        picker.state = "NY";
        picker.city = "New York";
        picker.street = "123 Main St";
        picker.zip = "10001";
    }
    getAddressData() {
        return {
            "countries": [
                { "code": "US", "name": "United States" },
                { "code": "CA", "name": "Canada" },
                { "code": "CN", "name": "China" },
                { "code": "GB", "name": "United Kingdom" },
                { "code": "JP", "name": "Japan" },
                { "code": "DE", "name": "Germany" },
                { "code": "AU", "name": "Australia" },
                { "code": "IN", "name": "India" },
                { "code": "FR", "name": "France" },
                { "code": "BR", "name": "Brazil" },
                { "code": "RU", "name": "Russia" },
                { "code": "KR", "name": "South Korea" },
                { "code": "MX", "name": "Mexico" }
            ],

            "states": {
                "US": ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "NY", "TX", "WA"],
                "CA": ["AB", "BC", "MB", "NB", "NL", "NS", "ON", "PE", "QC", "SK"],
                "CN": ["Beijing", "Shanghai", "Guangdong", "Jiangsu", "Zhejiang", "Sichuan"],
                "GB": ["England", "Scotland", "Wales", "Northern Ireland"],
                "JP": ["Tokyo", "Osaka", "Kyoto", "Hokkaido", "Fukuoka"],
                "DE": ["Bavaria", "Berlin", "Hamburg", "Hesse", "Lower Saxony"],
                "AU": ["NSW", "Victoria", "Queensland", "WA", "South Australia"],
                "IN": ["Maharashtra", "Delhi", "Karnataka", "Tamil Nadu", "West Bengal"],
                "FR": ["Île-de-France", "Provence-Alpes-Côte d'Azur", "Auvergne-Rhône-Alpes"],
                "BR": ["São Paulo", "Rio de Janeiro", "Minas Gerais", "Bahia"],
                "RU": ["Moscow Oblast", "Saint Petersburg", "Krasnodar Krai", "Tatarstan"],
                "KR": ["Seoul", "Busan", "Incheon", "Daegu", "Gyeonggi"],
                "MX": ["Mexico City", "Jalisco", "Nuevo León", "Veracruz"]
            },

            "cities": {
                // 美国
                "AL": ["Birmingham", "Montgomery", "Mobile"],
                "NY": ["New York", "Buffalo", "Rochester"],
                "CA": ["Los Angeles", "San Francisco", "San Diego"],

                // 加拿大
                "ON": ["Toronto", "Ottawa", "Mississauga"],
                "QC": ["Montreal", "Quebec City", "Laval"],

                // 中国
                "Beijing": ["Beijing"],
                "Shanghai": ["Shanghai"],
                "Guangdong": ["Guangzhou", "Shenzhen", "Dongguan"],

                // 英国
                "England": ["London", "Manchester", "Birmingham"],
                "Scotland": ["Edinburgh", "Glasgow", "Aberdeen"],

                // 日本
                "Tokyo": ["Tokyo", "Shibuya", "Shinjuku"],
                "Osaka": ["Osaka", "Sakai", "Toyonaka"],

                // 德国
                "Bavaria": ["Munich", "Nuremberg", "Augsburg"],
                "Berlin": ["Berlin"],

                // 澳大利亚
                "NSW": ["Sydney", "Newcastle", "Wollongong"],
                "Victoria": ["Melbourne", "Geelong", "Ballarat"],

                // 印度
                "Maharashtra": ["Mumbai", "Pune", "Nagpur"],
                "Delhi": ["New Delhi", "Noida", "Gurgaon"],

                // 法国
                "Île-de-France": ["Paris", "Versailles", "Boulogne-Billancourt"],

                // 巴西
                "São Paulo": ["São Paulo", "Campinas", "Guarulhos"],

                // 俄罗斯
                "Moscow Oblast": ["Moscow", "Khimki", "Balashikha"],

                // 韩国
                "Seoul": ["Seoul"],
                "Busan": ["Busan"],

                // 墨西哥
                "Mexico City": ["Mexico City", "Iztapalapa", "Coyoacán"]
            }
        }
    }

}
document.addEventListener('DOMContentLoaded',
    async function () {
        const localeUtil = new Locale();
        const systemLocalStorage = new SystemLocalStorage();
        await localeUtil.translate(systemLocalStorage.locale, "template-account-register", "content-account-register");
        const form = document.querySelector('.input-validation-required');
        const register = new Register();
        register.loading = document.querySelector('wcs-loading-bounce');
        await Promise.all([
            customElements.whenDefined('sl-button'),
            customElements.whenDefined('sl-checkbox'),
            customElements.whenDefined('sl-input'),
            customElements.whenDefined('sl-option'),
            customElements.whenDefined('sl-select'),
            customElements.whenDefined('sl-textarea')
        ]).then(() => {
            register.websocket();
            form.addEventListener('submit', event => {
                event.preventDefault();
                const data = serialize(form);
                const picker = document.querySelector('wcs-selector-address');
                data.address = {};
                data.address.country = picker.country;
                data.address.state = picker.state;
                data.address.city = picker.city;
                data.address.street = picker.street;
                data.address.zip = picker.zip;
                data.email = {};
                data.email.value = data.emailValue;
                register.register(data)
            });
        });
    }
);
